<?php

    /*
        mysql_query("truncate T_PHONEOPERATOR");
        mysql_query("truncate SMS_BILLING_UNIT");
    */

    /*
    * Находит в тексте и автоматически преобразует адреса, начинающиеся с ftp://, http://, https:// в активные ссылки.
    * $text = preg_replace("#(https?|ftp)://\S+[^\s.,>)\];'\&quot;!?]#", '<a href="\\0">\\0</a>', $text);
    */

    $mikron->Site->main();
    
    /**
    * Show debug info on float-panel
    */
    $mikron->Handlers->AddPageCompleteHandler('PageCompleteHandler', $mikron->Tools);

    // Реферал
    if(isset($_GET['r']))
    {
        setcookie("referal", $_GET['r'], time()+3600*24*365, "/");
    }
    if(($pos = strpos($_SERVER['REQUEST_URI'], "/player/")) !== false)
    {
        $adr = substr($_SERVER['REQUEST_URI'], $pos + 8);
        if(($pos = strpos($adr, "/")) !== false)
        {
            $adr = substr($adr, 0, $pos);
        }
        setcookie("referal", $adr, time()+3600*24*365, "/");
        ob_clean();
        header("Location: /");
        exit;
    }

    function GoToPage($uri)
    {
        $out = ob_get_clean();
        header('Location: '.$uri);
        exit;
    }

    function startform($ok = true)
    {
        ?><div id="mesformdisplay"><?php
        if($ok)
        {
            startxform("Выполнено", clearscriptname(), "mesform", "get", "_silver", true);
        }
        else
        {
            startxform("Ошибка", clearscriptname(), "mesform", "get", "_silver", true);
        }
        ?>
        <table cellspacing="0" cellpadding="4">
        <tr><td>
        <?php
    }

    function endform()
    {
        ?>
        </td></tr>
        <tr><td>
            <input type="submit" onclick="mesformdisplay.style.display='none'; return false;" value="Закрыть">
        </table>
        <?php endxform(true); ?></div><?php
    }

    function clearscriptname()
    {
        // return $_SERVER['SCRIPT_NAME'];
        $ret = $_SERVER['REQUEST_URI'];
        $pos = strpos($ret, "?");
        if($pos === false)
        {
            return $ret;
        }
        else
        {
            return substr($ret, 0, $pos);            
        }
    }

    function getLastWinners()
    {
        getLastWinners_function();
        /*
        global $mikron;
        echo $mikron->Cache->TimedFunctionContent('short_stat', 'getLastWinners_function', 420);
        */
    }
    
    function getLastWinners_function()
    {
        global $mikron;
        $all = $mikron->EntityManager->QueryCount('T_WIN', null, null);
        $today = $mikron->EntityManager->QueryCount('T_WIN', null, new Criterion('dt', date($mikron->Constants->DateFormatMySQL), CR_MOREOREQUAL));
        $cr = new Criteria();
        $cr->add(new Criterion('dt', date($mikron->Constants->DateFormatMySQL, time() - 86400), CR_MOREOREQUAL));
        $cr->add(new Criterion('dt', date($mikron->Constants->DateFormatMySQL), CR_LESS));
        $yesterday = $mikron->EntityManager->QueryCount('T_WIN', null, $cr);
        $sum = 0;
        $wins = $mikron->Queries->Query('T_WIN', null, null, null, null, null, false, Array('amount'));
        while($win = $wins->fetch())
        {
            $sum += $win->amount->value;
        }
        $sum = $sum / 100;
        echo "<h1>Краткая статистика:</h1>Выигранных игр всего <font color=\"1D9E03\">$all</font>,
        из них сегодня <font color=\"1D9E03\">$today</font>,
        вчера <font color=\"1D9E03\">$yesterday</font>,
        общая сумма выигрышей на проекте <font color=\"1D9E03\">$sum"."р.</font>";
        
        $t = new html_table(2, 'table2', '100%');
        $t->newcol('Последние 7 выигрышей', false, false, null, 'table2_header', null, null, null, 2);
        $wins = $mikron->Queries->Query('T_WIN', null, null, null, '0,7');
        while($win = $wins->fetch())
        {
            $t->newcol($win->cabinet->value->login->value.'<font class="hiddentext"> ('.$win->game->value->name->value.')</font>');
            $t->newcol(round($win->amount->value/100, 2).'р.', true, 'right');
            //$t->newcol($win->game->value->name->value, false, false, null, 'table2_smallcell');
            //$t->newcol(MikronDateTime::BeautifulDate(strtotime($win->dt->value), false), true, 'right', null, 'table2_smallcell');
        }
        $t->newcol('7 лучших победителей', false, false, null, 'table2_header', null, null, null, 2);
        $users = $mikron->Queries->Query('T_USER', null, null, '`winamount` DESC', '0,7', null, false, Array('login', 'winamount'));
        while($user = $users->fetch())
        {
            $t->newcol($user->login->value);
            $t->newcol(round($user->winamount->value/100, 2).'р.', true, 'right');
        }
        $t->newcol('* Статистика обновляется каждые 7 минут.', false, false, null, 'table2_smallcell_noborder', null, null, null, 2);
        $t->end();
        
    }

    function getAccount()
    {
        global $mikron;

        if($mikron->ACL->hasRole('admin'))
        {
            echo '{{MIKRON_USERFORM cabinetadr="/" enterclass="loginicon"
                exitclass="logouticon"}}<br />';
            return;
        }

        if(!$mikron->Users->Logged())
        {
            echo '{{MIKRON_USERFORM cabinetadr="/" enterclass="loginicon"
                exitclass="logouticon"}}<br />';
            return;
        }
        $user = $mikron->Users->CurrentUser()->user;
        $table1 = new html_table(1, null, '100%');
        /*$table1->newcol(null, false, 'center');
            if(is_null($user->picture->value))
            {
                $mikron->Tools->ShowPicture('/images/nophoto.gif', $user->login->value, 'center');
            }
            else
            {
                $mikron->Tools->ShowPicture($user->picture->value, $user->login->value, 'center');
            }
        */
        $table1->newcol();
            echo '{{MIKRON_USERFORM cabinetadr="/" hideexitbutton="1" enterclass="loginicon"
                exitclass="logouticon"}}';
        $table1->newcol();
            $amount = $user->amount->value;
            echo sprintf('<h1>Баланс &mdash; %s руб.</h1>', round($amount/100,2));
        $table1->newcol();
                
                /**
                * Создание и отрисовка меню
                */
                function DrawLocalMenu($local_menu_items)
                {
                    $tab = new html_table(1);
                    foreach($local_menu_items as $item)
                    {
                        $href = $item[0];
                        $title = $item[1];
                        $iconclass = $item[2];
                        $text = $item[3];
                        $tab->newcol(sprintf('{{iconlink href="%s" title="%s" iconclass="%s" text="%s"}}', $href, $title, $iconclass, $text));
                    }
                    $tab->end();
                }
                $local_menu_items = Array();
                $local_menu_items[] = Array('/?gamerpage=freegames', 'Перейти на страницу аккаунта', 'myaccicon', 'Мой аккаунт');
                if(!is_null($referal = $user->referal->value))
                {
                    $local_menu_items[] = Array('/friends/', 'Перейти на страницу со списком моих друзей', 'myfriends', 'Друзья');
                }
                $local_menu_items[] = Array('/user/'.$referal->login->value.'/', 'Открыть страницу партнера', 'helpicon', 'Мой партнер');
                $local_menu_items[] = Array('/?logout', 'Закрыть аккаунт', 'logouticon', 'Выход');
                DrawLocalMenu($local_menu_items);

        $table1->end();
    }

    // Главное меню
    function getMenu($parameters)
    {
        global $mikron;
        $cat = (int)$parameters['category'];
        if($cat == 2)
        {
            if(!$mikron->ACL->hasRole('admin'))
            {
                return false;
            }
        }
        $items = $mikron->Queries->Query('T_MENU', null, new Criterion('menugroup', $cat));
        $curpage = $mikron->Page->getCurrentPage();
        while($item = $items->fetch())
        {
            $title = $item->title->value;
            $url = $item->toURL();
            if($curpage == $url)
            {
                ?><span class="whitelinkselectedlink"><?php echo $title;?></span><?php
            }
            else
            {
                ?><a class="whitelink" href="<?php echo $url;?>"><?php echo $title;?></a><?php
            }
            echo "&nbsp;&nbsp;&nbsp;";
        }
    }

    function createpuy($wmr, $summa, $comment="", $title="")
    {
        if($title==""){$title=$wmr;}
        $summa2 = $summa / 100;
        return "<a href=\"wmk:payto?Purse=".$wmr."&Amount=".$summa2."&Desc=".urlencode($comment)."&BringToFront=Y\">".$title."</a>";
    }

    function getChipsName($code)
    {
        try
        {
            global $mikron;
            $marketitems = $mikron->Queries->Query('MARKET_ITEM');
            while($item = $marketitems->fetch())
            {
                if($item->code->value==$code)
                {
                    return $item->title->value;
                }
            }
            return null;
        }
        catch(Exception $ex)
        {
            return null;
        }
    }

    function getCity($ipadr = null)
    {
        global $mikron;
        $city = $mikron->Cache->getCache("usercity");
        if(!is_null($city))
        {
            return $city;
        }
        // return "Казань";
        if(is_null($ipadr))
        {
            $ipadr = $_SERVER["REMOTE_ADDR"];
        }
        $data = "<ipquery><fields><city/></fields><ip-list><ip>$ipadr</ip></ip-list></ipquery>";
        $url = "http://194.85.91.253:8090/geo/geo.html";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url); // set url to post to
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);// allow redirects
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
        curl_setopt($ch, CURLOPT_TIMEOUT, 3); // times out after 4s
        curl_setopt($ch, CURLOPT_POST, 1); // set POST method
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // add POST fields
        $result = curl_exec($ch); // run the whole process
        curl_close($ch);
        // $result = iconv("windows-1251", "UTF-8", $result);
        // echo $result;
        $doc = new DOMDocument();
        $doc->loadXML($result);
        $content = $doc->getElementsByTagname('ip-answer');
        $city = null;
        foreach($content as $value)
        {
            $ip_blocks = $value->getElementsByTagname('ip');
            foreach($ip_blocks as $ip_value)
            {
                if($ip_value->hasAttribute('value'))
                {
                    $ip = $ip_value->getAttribute('value');
                    
                    $city_value = $ip_value->getElementsByTagname('city');
                    foreach($city_value as $cities)
                    {
                        $city = $cities->nodeValue;
                    }
                }
            }
        }
        unset($content);
        $mikron->Cache->setCache("usercity", is_null($city)?'Unknown':$city);
        return $city;
    }

?>